import { defineEventHandler, readBody } from 'h3';
import { generateId } from '../types/index.js';

export function createRulesApi(app) {
  return defineEventHandler(async (event) => {
    if (event.node.req.method === 'GET') {
      const rules = app.database.getRules();
      return { data: rules };
    }

    if (event.node.req.method === 'POST') {
      const body = await readBody(event);
      const rule = {
        id: generateId(),
        name: body.name,
        description: body.description,
        enabled: body.enabled ?? true,
        conditions: body.conditions || [],
        actions: body.actions || [],
        createdAt: Date.now(),
        updatedAt: Date.now()
      };

      app.database.saveRule(rule);
      app.ruleEngine.addRule(rule);

      // 通过WebSocket通知前端
      app.webSocketServer.broadcast({
        type: 'rule_created',
        data: rule,
        timestamp: Date.now()
      });

      return { data: rule };
    }
  });
}

export function createRuleDetailApi(app) {
  return defineEventHandler(async (event) => {
    const id = event.context.params.id;

    if (event.node.req.method === 'PUT') {
      const body = await readBody(event);
      const rule = {
        ...body,
        id,
        updatedAt: Date.now()
      };

      app.database.saveRule(rule);
      app.ruleEngine.updateRule(rule);

      // 通过WebSocket通知前端
      app.webSocketServer.broadcast({
        type: 'rule_updated',
        data: rule,
        timestamp: Date.now()
      });

      return { data: rule };
    }

    if (event.node.req.method === 'DELETE') {
      const success = app.database.deleteRule(id);
      if (success) {
        app.ruleEngine.removeRule(id);

        // 通过WebSocket通知前端
        app.webSocketServer.broadcast({
          type: 'rule_deleted',
          data: { id },
          timestamp: Date.now()
        });

        return { success: true };
      } else {
        event.node.res.statusCode = 404;
        return { error: 'Rule not found' };
      }
    }
  });
} 